package com.topvision.camerasdk.video;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.CamcorderProfile;
import android.media.SoundPool;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StatFs;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.topvision.camerasdk.R;
import com.topvision.camerasdk.album.MyAblumActivity;
import com.topvision.camerasdk.camera.CameraConstants;
import com.topvision.camerasdk.camera.util.CameraUtil;
import com.topvision.camerasdk.video.Interface.VideoInterface;
import com.topvision.camerasdk.video.receiver.HomeClickReceiver;
import com.topvision.camerasdk.video.test.FocusImageView;
import com.topvision.camerasdk.video.test.SensorControler;
import com.topvision.camerasdk.video.util.VideoConstant;
import com.topvision.commomsdk.TouchInterface;
import com.topvision.commomsdk.activity.BaseActivity;
import com.topvision.commomsdk.uitl.AndroidUtils;
import com.topvision.commomsdk.uitl.DateUtil;
import com.topvision.commomsdk.uitl.PreferencesUtils;
import com.topvision.commomsdk.view.TvPopWindow;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


/**
 * The type Media recorder activity.
 */
public class MediaRecorderActivity extends BaseActivity implements
        TouchInterface, View.OnClickListener {
    /**
     * The constant RECORD_FINSH.
     */
    public static final int RECORD_FINSH = 1;
    /**
     * The constant HANDLER_UPDATE_ALBUM.
     */
    public static final int HANDLER_UPDATE_ALBUM = 2;
    public static final int HANDLER_START_RECORDING = 3;
    private static final long VIDEO_AT_LEAST_TIME = 2000;
    //录制最长时间参数(1h) 1*60*60;
    private static final long VIDEO_RECORD_MAX_TIME = 1 * 60 * 60;
    // 记录开始录制的毫秒数
    private long startTime = 0;
    // 开始录制和停止录制按钮
    private ImageView startIv, endIv;
    // 當前錄製視屏的随机一帧图片
    private Bitmap currPhoto;
    // 相册图片空间
    private ImageView albumIv;
    private TextView tv_time_, voiceTips;
    private ImageView im_flash;
    private ImageView im_black;
    private View view_album;
    private int state = 1;
    /**
     * The Is recording.
     */
    boolean isRecording = true;// 录制
    private CameraPreview mPreview;
    // 存放预览画面的layout
    private FrameLayout preview;
    private String name;
    private long clickTakeVideoTime = 0;
    private boolean isDeleting = false;
    private double parseDouble;// 内存
    /**
     * The Voice service is run.
     */
    boolean VoiceServiceIsRun;
    /**
     * The Save path.
     */
    String savePath;
    /**
     * The Voice tip flag.
     */
    boolean voiceTipFlag;
    /**
     * The constant TAKE_VIDEO_FOLDER.
     */
//如果传过来的保存路径为空,则给默认视频路径
    public static String TAKE_VIDEO_FOLDER = VideoConstant.mediaFolderPath;
    /**
     * The Msg save path.
     */
    String msgSavePath;

    Context context;
    //外置sdcard地址
    String sdcardPath = "";
    //内存满了之后。删除最前面的5个文件
    final int REMOVE_FILE_COUNT = 5;
    SensorControler mSensorControler;
    /**
     * 触摸屏幕时显示的聚焦图案
     */
    private FocusImageView mFocusImageView;
    public static Activity mActivity;
    //默认块状大小为5M
    public final int blockLength = 5 * 1024 * 1024;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);// 强制为横屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        context = this;
        mActivity = this;
        setContentView(R.layout.activity_media_recorder);
        final DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);


        initViews();
        mSensorControler = SensorControler.getInstance(context);
        mSensorControler.setCameraFocusListener(new SensorControler.CameraFocusListener() {
            @Override
            public void onFocus() {
                Point point = new Point(metric.widthPixels / 2, metric.heightPixels / 2);
                onCameraFocus(point);
            }
        });

        //注册Home键监听广播
        // registerHomeClickReceiver();
    }

    /**
     * 获取保存路径,如果有外置则放入外置,没有则放入内置sdcard
     * create at 2017/2/16 16:18
     */
    private void getSavePath() {
        sdcardPath = AndroidUtils.getExtSDCardPath(context);
//        sdcardPath = AndroidUtils.getSDCardPath();
        //有外置sdcard
        if (!TextUtils.isEmpty(sdcardPath)) {
            TAKE_VIDEO_FOLDER = sdcardPath + VideoConstant.MEDIA_FOLDER;
        } else {
            TAKE_VIDEO_FOLDER = VideoConstant.mediaFolderPath;
        }
        getMsg();
        savePath = getIntent().getStringExtra(CameraConstants.SAVE_PATH);
        voiceTipFlag = getIntent().getBooleanExtra(CameraConstants.VOICE_TIPS_FLAG, false);
        //换成用户传来的视频地址路径
        if (!TextUtils.isEmpty(savePath)) {
            TAKE_VIDEO_FOLDER = savePath;
        }
        //不需要显示语音提示
//        voiceTips.setVisibility(View.GONE);
        //提示用户语音控制无效
        if (voiceTipFlag) {
            AndroidUtils.showTips(this, "摄像机内语音控制将失效");
        }
        if (!TextUtils.isEmpty(msgSavePath)) {
            TAKE_VIDEO_FOLDER = msgSavePath;
        }
    }

    private void initViews() {
        view_album = findViewById(R.id.view_album);
        albumIv = (ImageView) findViewById(R.id.album_iv);
        preview = (FrameLayout) findViewById(R.id.camera_preview);
        // 录制
        startIv = (ImageView) findViewById(R.id.start_iv);
        endIv = (ImageView) findViewById(R.id.end_iv);
        tv_time_ = (TextView) findViewById(R.id.tv_time_);
        im_flash = (ImageView) findViewById(R.id.im_flash);
        im_black = (ImageView) findViewById(R.id.im_black);
        voiceTips = (TextView) findViewById(R.id.tips);

        mFocusImageView = (FocusImageView) findViewById(R.id.focusImageView);
        if (AndroidUtils.isBtDevice()) {
            registClickListener();
            currentMode = MODE_SWIPE;
            hideStateTag();
        } else {
            stateTag();
        }
    }

    private void registClickListener() {
        startIv.setOnClickListener(this);
        endIv.setOnClickListener(this);
        albumIv.setOnClickListener(this);
        im_flash.setOnClickListener(this);
        im_black.setOnClickListener(this);
    }

    private void unRegistClickListener() {
        startIv.setOnClickListener(null);
        endIv.setOnClickListener(null);
        albumIv.setOnClickListener(null);
        im_flash.setOnClickListener(null);
        im_black.setOnClickListener(null);
    }

    /**
     * 获取清单文件中传过来的值 用于我们luancher上的 摄像机
     * Get msg.
     */
    public void getMsg() {
        ActivityInfo info = null;
        try {
            info = this.getPackageManager().getActivityInfo(getComponentName(), PackageManager.GET_META_DATA);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        Bundle metaData = info.metaData;
        if (metaData != null) {
            msgSavePath = info.metaData.getString("msgVideoPath");
            System.out.println("msgVideoPath:" + msgSavePath);
        }
    }


    private void stateTag() {
        switch (state) {
            case 0://设置
                endIv.setImageResource(R.drawable.stop);
                startIv.setImageResource(R.drawable.video);
                im_black.setImageResource(R.drawable.back_unselected);
                im_flash.setImageResource(R.drawable.resolution_selected);
                view_album.setVisibility(View.GONE);
                break;
            case 1://录像
                endIv.setImageResource(R.drawable.stop_two);
                startIv.setImageResource(R.drawable.video_two);
                im_black.setImageResource(R.drawable.back_unselected);
                im_flash.setImageResource(R.drawable.resolution_unselected);
                view_album.setVisibility(View.GONE);
                break;
            case 2://返回
                endIv.setImageResource(R.drawable.stop);
                startIv.setImageResource(R.drawable.video);
                im_black.setImageResource(R.drawable.back_selected);
                im_flash.setImageResource(R.drawable.resolution_unselected);
                view_album.setVisibility(View.GONE);
                break;
            case 3://视频库
                startIv.setImageResource(R.drawable.video);
                endIv.setImageResource(R.drawable.stop);
                im_black.setImageResource(R.drawable.back_unselected);
                im_flash.setImageResource(R.drawable.resolution_unselected);
                view_album.setVisibility(View.VISIBLE);
                break;

        }

    }

    private void hideStateTag() {
        switch (state) {
            case 0:
                endIv.setImageResource(R.drawable.stop);
                startIv.setImageResource(R.drawable.video);
                im_black.setImageResource(R.drawable.back_unselected);
                im_flash.setImageResource(R.drawable.resolution_unselected);
                view_album.setVisibility(View.GONE);
                break;
            case 1:
                endIv.setImageResource(R.drawable.stop);
                startIv.setImageResource(R.drawable.video);
                im_black.setImageResource(R.drawable.back_unselected);
                im_flash.setImageResource(R.drawable.resolution_unselected);
                view_album.setVisibility(View.GONE);
                break;
            case 2:
                endIv.setImageResource(R.drawable.stop);
                startIv.setImageResource(R.drawable.video);
                im_black.setImageResource(R.drawable.back_selected);
                im_flash.setImageResource(R.drawable.resolution_unselected);
                view_album.setVisibility(View.GONE);
                break;
            case 3:
                endIv.setImageResource(R.drawable.stop);
                startIv.setImageResource(R.drawable.video);
                im_black.setImageResource(R.drawable.back_unselected);
                im_flash.setImageResource(R.drawable.resolution_unselected);
                view_album.setVisibility(View.GONE);
                break;
        }
    }

    /**
     * Init camera.
     */
    public void initCamera() {
        mPreview = new CameraPreview(this);
        preview.addView(mPreview, FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT);

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.start_iv || id == R.id.end_iv) {
            if (isRecording) {
                size();
            } else {
                stopRecording(albumIv);
            }
        } else if (id == R.id.album_iv) {
            if (!isRecording) {
                stopRecording(albumIv);
            }
            Intent intent1 = new Intent(MediaRecorderActivity.this, MyAblumActivity.class);
            intent1.putExtra(VideoConstant.ABLUM_TYPE, VideoConstant.ABLUM_TYPE_MEDIA);
            intent1.putExtra(CameraConstants.VOICE_TIPS_FLAG, false);
            startActivity(intent1);

        } else if (id == R.id.im_flash) {
            if (!isRecording) {
                stopRecording(albumIv);
            }
            Intent intent = new Intent(MediaRecorderActivity.this, VideoSettingActivity.class);
            startActivity(intent);
        } else if (id == R.id.im_black) {
            if (!isRecording) {
                stopRecording(albumIv);
            }
            finish();
        }
    }


    /**
     * 设置相册最新的背景图
     *
     * @author jack
     *         create at 2016/11/21 13:45
     */
    class FileAsyncTask extends AsyncTask<String, Void, File> {


        @Override
        protected File doInBackground(String... strings) {
            //获取拍照目录下最新的缩略图显示在相册上
            File file = CameraUtil.getNewestVideoFile(context);
            return file;
        }

        @Override
        protected void onPostExecute(File file) {
            super.onPostExecute(file);
            if (file != null && file.exists() && file.length() > 0) {
                Picasso.with(context).load(file).into(albumIv);
            } else {
                Picasso.with(context).load(R.mipmap.xiangce).into(albumIv);
            }
        }
    }

    /**
     * 获得sd卡剩余容量，即可用大小
     *
     * @param context the context
     * @return sd available size
     */
    public static String getSDAvailableSize(Context context, String sdcardPath) {
//        File path = Environment.getExternalStorageDirectory();
        StatFs stat = new StatFs(sdcardPath);
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return Formatter.formatFileSize(context, blockSize * availableBlocks);
    }

    private void size() {
        getSavePath();
        //外置sdcard不存在,则保存在内置sdcard上
        if (TextUtils.isEmpty(sdcardPath)) {
            if (!hasMoreSpace(Environment.getExternalStorageDirectory().getPath())) {
//                CameraUtil.removeEarlyVideos(context, REMOVE_FILE_COUNT);
                AndroidUtils.showTips(context, getString(R.string.sdcard_storage_full));
                return;
            }
            tv_time_.setText("");
            isRecording = false;
            startIv.setVisibility(View.GONE);
            endIv.setVisibility(View.VISIBLE);
            videoInterface.isRecording(true);
            mPreview.startRecording();

            clickTakeVideoTime = System.currentTimeMillis();
            startTime = System.currentTimeMillis();
        } else {
            if (!hasMoreSpace(sdcardPath)) {
                if (!hasMoreSpace(Environment.getExternalStorageDirectory().getPath())) {
                    // CameraUtil.removeEarlyVideos(context, REMOVE_FILE_COUNT);
                    AndroidUtils.showTips(context, getString(R.string.sdcard_storage_full));
                    return;
                }
            }
            tv_time_.setText("");
            isRecording = false;
            startIv.setVisibility(View.GONE);
            endIv.setVisibility(View.VISIBLE);
            videoInterface.isRecording(true);
            mPreview.startRecording();
            clickTakeVideoTime = System.currentTimeMillis();
            startTime = System.currentTimeMillis();
        }
    }

    /**
     * 判断该路径下是否还有保存空间了
     * create at 2017/2/16 17:07
     */
    private boolean hasMoreSpace(String sdcardPath) {
        String sdAvailableSize = getSDAvailableSize(context, sdcardPath);
        if (sdAvailableSize.contains("G")) {
            String sdMemory[] = sdAvailableSize.split("G");
            parseDouble = Double.parseDouble(sdMemory[0]);
            parseDouble = parseDouble * 1024;
        } else {
            String sdMemory[] = sdAvailableSize.split("M");
            parseDouble = Double.parseDouble(sdMemory[0]);
        }
        if (parseDouble < 100.0) {
            return false;
        }
        System.out.println("当前可用:" + parseDouble + "M");
        return true;
    }

    private void initEvents() {
        mPreview.setMvideoInterface(videoInterface);
    }

    /**
     * 录制视频回调接口
     */
    VideoInterface videoInterface = new VideoInterface() {
        private final int HANDLER_COUNT_DOWN_TIME = 1;

        Handler handlerTime = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == HANDLER_COUNT_DOWN_TIME) {
                    // 计时
                    long elapsed = System.currentTimeMillis() - startTime;
                    tv_time_.setText(DateUtil.transformHMS(elapsed));
                    //说明没有外置sdcard
                    if (TextUtils.isEmpty(sdcardPath)) {
                        if (!hasMoreSpace(Environment.getExternalStorageDirectory().getPath())) {
                            stopRecording(albumIv);
                            AndroidUtils.showTips(context, getString(R.string.sdcard_storage_full));
                            //showNoMoreSpace();
                            return;
                        }
                    } else {
                        if (!hasMoreSpace(sdcardPath)) {
                            // showNoMoreSpace();
                            stopRecording(albumIv);
                            AndroidUtils.showTips(context, getString(R.string.sdcard_storage_full));
                            return;
                        }
                    }

                    //录制在外置sdcard的时候,会有4G视频大小的限制
                    /*if (!TextUtils.isEmpty(sdcardPath)) {
                        File currentRecordFile = mPreview.getmVecordFile();
                        if (currentRecordFile != null && currentRecordFile.exists() && currentRecordFile.length() > VideoConstant.MAX_RECORD_VIDEO_SIZE) {
                            handlerTime.removeMessages(HANDLER_COUNT_DOWN_TIME);
                            recordNext();
                            return;
                        }
                    }*/
                    File currentRecordFile = mPreview.getmVecordFile();
                    if (currentRecordFile != null && currentRecordFile.exists() && currentRecordFile.length() > VideoConstant.MAX_RECORD_VIDEO_SIZE) {
                        handlerTime.removeMessages(HANDLER_COUNT_DOWN_TIME);
                        recordNext();
                        return;
                    }

                    //继续循环
                    handlerTime.sendEmptyMessageDelayed(HANDLER_COUNT_DOWN_TIME, 1000);
                }
            }

        };

        @Override
        public void isRecording(Boolean flash) {
            if (flash) {
                handlerTime.sendEmptyMessageDelayed(1, 1000);
                tv_time_.setVisibility(View.VISIBLE);
            } else {
                startTime = 0;
                tv_time_.setVisibility(View.GONE);
                handlerTime.removeCallbacksAndMessages(null);
            }
        }

        @Override
        public void black() {// 关闭摄像机
            MediaRecorderActivity.this.finish();
        }
    };


    /**
     * 录制下个视频文件
     * create at 2017/3/30 10:11
     */
    public void recordNext() {
        stopRecording(albumIv);
        Message message = new Message();
        message.what = HANDLER_START_RECORDING;
        handler.sendMessageDelayed(message, 2000);
    }

    /**
     * The Handler.
     */
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RECORD_FINSH:
                    // 更改图标状态
                    startIv.setVisibility(View.VISIBLE);
                    endIv.setVisibility(View.GONE);
                    break;
                case HANDLER_UPDATE_ALBUM:
                    if (System.currentTimeMillis() - clickTakeVideoTime > VIDEO_AT_LEAST_TIME) {
                        Bitmap tempBitmap = (Bitmap) msg.obj;
                        if (tempBitmap != null) {
                            albumIv.setImageBitmap(tempBitmap);
                            saveMyBitmap(tempBitmap, name);
                        } else {
                            albumIv.setBackgroundResource(R.mipmap.xiangce);
                        }
                    }
                    break;
                case HANDLER_START_RECORDING:
                    size();
                    break;

            }
        }
    };


    @Override
    protected void onResume() {
        super.onResume();
        // 获取视频集合
        new FileAsyncTask().execute();
        setTouchInterfaceListener(this);
        checkVoice();
        setTips();
        if (mPreview == null) {
            initCamera();
            initEvents();
        }
//        mSensorControler.onStart();
//        mSoundPool = getSoundPool();


    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mPreview.isRecording()) {
            stopRecording(albumIv);
        }
        preview.removeView(mPreview);
        mPreview.freeCameraResource();
        mPreview = null;

//        mSensorControler.onStop();
//        mSoundPool.release();
//        mSoundPool = null;

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (currPhoto != null) {
            currPhoto.recycle();
            currPhoto = null;
        }
        //  unRegisterHomeClickReceiver();
        checkVoice();
    }

    /**
     * 设置提示用户信息内容
     *
     * @param
     * @return void
     * @throws
     * @Title: setTips
     * @Description:目前只显示当前摄像机分辨率
     */
    private void setTips() {
        int resolution = PreferencesUtils.getInt(this,
                VideoSettingActivity.SHAREPREFERENCE_RESOLUTION,
                CamcorderProfile.QUALITY_480P);
        String strReslution = "";
        switch (resolution) {
            case CamcorderProfile.QUALITY_480P:
                strReslution = "480P";
                break;
            case CamcorderProfile.QUALITY_720P:
                strReslution = "720P";
                break;
            case CamcorderProfile.QUALITY_1080P:
                strReslution = "1080P";
                break;
            default:
                break;
        }
        if (voiceTips != null) {
            voiceTips.setText(getString(R.string.version_name) + AndroidUtils.getVersion(context) + "\n" + getString(R.string.resolution) + strReslution);
        }
    }

    String mp4name = "";
    File getmVecordFile = null;

    private void stopRecording(ImageView ablumIv) {
        if (System.currentTimeMillis() - clickTakeVideoTime > VIDEO_AT_LEAST_TIME) {
            mPreview.stopRecording(handler, ablumIv);
            startIv.setVisibility(View.VISIBLE);
            endIv.setVisibility(View.GONE);
            isRecording = true;
            getmVecordFile = mPreview.getmVecordFile();
            mp4name = getmVecordFile.getName();
            name = mp4name.replace("mp4", "jpg");
            startTime = 0;

            //取消视频自动上传功能
//            //发送广播,让Launcher 自动上传视频
//            Intent intent = new Intent("com.topvision.action.video.upload");
//            intent.putExtra("upload_file_path", getmVecordFile.getAbsolutePath());
//            intent.putExtra("blockLength", blockLength);
//            sendBroadcast(intent);
        }
    }

    /**
     * Save my bitmap.
     *
     * @param mBitmap the m bitmap
     * @param bitName the bit name
     */
    public void saveMyBitmap(Bitmap mBitmap, String bitName) {
        File f = new File(CameraConstants.THUMBNAIL_FOLDER + bitName);
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);

        try {
            fOut.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (f.exists()) {
            AndroidUtils.fileScan(context, f.getPath());
            AndroidUtils.fileScan(context, f.getPath().replace(".jpg", ".mp4"));
        }
        if (getmVecordFile != null && getmVecordFile.exists()) {
            AndroidUtils.fileScan(context, getmVecordFile.getPath());
        }
    }

    @Override
    public void doForwardTouch() {
        if (currentMode == MODE_BUTTON) {
            if (!isDeleting) {
                if (state == 3) {
                    return;
                }
                state = state + 1;
                stateTag();
            }
        }
    }

    @Override
    public void doBackwardTouch() {
        if (currentMode == MODE_BUTTON) {
            if (!isDeleting) {
                if (state == 0) {
                    return;
                }
                state = state - 1;
                stateTag();
            }
        }
    }

    @Override
    public void doClickTouch() {
        if (currentMode == MODE_BUTTON) {
            if (!isDeleting) {
                onClick();
            }
        }
    }

    private int currentMode = 0;
    private static final int MODE_BUTTON = 0;//按钮模式
    private static final int MODE_SWIPE = 1;//BT300滑动点击模式

    @Override
    public void doDoubleTouch() {
        //bt300操作
        if (AndroidUtils.isBtDevice()) {
            if (currentMode == MODE_BUTTON) {
                //切换为滑动点击模式
                currentMode = MODE_SWIPE;
                registClickListener();
                hideStateTag();
            } else {
                currentMode = MODE_BUTTON;
                unRegistClickListener();
                stateTag();
            }
        }
    }

    private void onClick() {
        switch (state) {
            case 0:
                if (!isRecording) {
                    stopRecording(albumIv);
                }
                im_flash.setImageResource(R.drawable.resolution_selected);
                Intent intent = new Intent(MediaRecorderActivity.this, VideoSettingActivity.class);
                startActivity(intent);
                break;
            case 1:
                if (isRecording) {
                    size();
                } else {
                    stopRecording(albumIv);
                }
                break;
            case 2:
                if (!isRecording) {
                    stopRecording(albumIv);
                }
                finish();
                break;
            case 3:
                if (!isRecording) {
                    stopRecording(albumIv);
                }
                Intent intent1 = new Intent(MediaRecorderActivity.this, MyAblumActivity.class);
                intent1.putExtra(VideoConstant.ABLUM_TYPE, VideoConstant.ABLUM_TYPE_MEDIA);
                intent1.putExtra(CameraConstants.VOICE_TIPS_FLAG, false);
                startActivity(intent1);
                break;
        }
    }

    /**
     * Check voice.
     */
    public void checkVoice() {
        VoiceServiceIsRun = AndroidUtils.isServiceRun(this, VideoConstant.VOICETRACK_SERIVCE_NAME);
        CameraUtil.controlVocie(this, VoiceServiceIsRun);
    }


    @Override
    protected void onStart() {
        super.onStart();


    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    /**
     * 相机对焦  默认不需要延时
     *
     * @param point
     */
    private void onCameraFocus(final Point point) {
        onCameraFocus(point, false);
    }

    /**
     * 相机对焦
     *
     * @param point
     * @param needDelay 是否需要延时
     */
    public void onCameraFocus(final Point point, boolean needDelay) {
        long delayDuration = needDelay ? 300 : 0;

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!mSensorControler.isFocusLocked()) {
                    //聚焦之后根据结果修改图片
                    mSensorControler.lockFocus();
                    if (mPreview != null && mPreview.onFocus(point, autoFocusCallback)) {
                        // mSensorControler.lockFocus();
                        //  mFocusImageView.startFocus(point);
                        //播放对焦音效
                        if (mFocusSoundPrepared) {
                            mSoundPool.play(mFocusSoundId, 1.0f, 0.5f, 1, 0, 1.0f);
                        }
                    }
                }
            }
        }, delayDuration);
    }


    TvPopWindow tvPopWindow;

    public void showNoMoreSpace() {
        if (tvPopWindow == null) {
            tvPopWindow = new TvPopWindow(MediaRecorderActivity.this);
        }
        tvPopWindow.setContent("内存满了");
        tvPopWindow.showAtLocation(findViewById(R.id.media_recorder_parent), Gravity.CENTER, 0, 0);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

        }
    };


    private final Camera.AutoFocusCallback autoFocusCallback = new Camera.AutoFocusCallback() {

        @Override
        public void onAutoFocus(boolean success, final Camera camera) {
            if (success) {
                mFocusImageView.onFocusSuccess();
            } else {
                //聚焦失败显示的图片，由于未找到合适的资源，这里仍显示同一张图片
                mFocusImageView.onFocusFailed();
            }
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //一秒之后才能再次对焦
                    mSensorControler.unlockFocus();
                }
            }, 200);
        }
    };


    private SoundPool mSoundPool;
    private int mFocusSoundId;
    private boolean mFocusSoundPrepared;

    private SoundPool getSoundPool() {
        if (mSoundPool == null) {
            mSoundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
            mFocusSoundId = mSoundPool.load(context, R.raw.camera_focus, 1);
            mFocusSoundPrepared = false;
            mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
                @Override
                public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                    mFocusSoundPrepared = true;
                }
            });
        }
        return mSoundPool;
    }

    HomeClickReceiver homeClickReceiver;
    private static final String CAMERA_BUTTON = "android.intent.action.CAMERA_BUTTON";

    private void registerHomeClickReceiver() {
        // 注册广播接收
        homeClickReceiver = new HomeClickReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(CAMERA_BUTTON); // 只有持有相同的action的接受者才能接收此广播
        filter.setPriority(200);
        registerReceiver(homeClickReceiver, filter);
    }

    private void unRegisterHomeClickReceiver() {
        // 注册广播接收
        if (homeClickReceiver != null) {
            unregisterReceiver(homeClickReceiver);
        }
    }
}
